package com.nx.simple.producer;

import com.nx.Constant;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * SendResult
 *     SEND_OK,
 *     FLUSH_DISK_TIMEOUT,
 *     FLUSH_SLAVE_TIMEOUT,
 *     SLAVE_NOT_AVAILABLE,
 *  MessageId:IP+消息的偏移量构成，不能保证一定唯一，如果要求幂等操作，发送消息时给mesageKey(业务维护)
 */
public class SyncProducer {

    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {
        //Instantiate with a producer group name.
        DefaultMQProducer producer = new DefaultMQProducer("nx-group");
        // 如果网络不太好，可以设置一下超时时间
        producer.setSendMsgTimeout(10*1000);
        producer.setNamesrvAddr(Constant.MQ);
        // 发送失败的时候重试次数
        producer.setRetryTimesWhenSendFailed(2);
        producer.start();



        for(int i  =0 ;i < 5; i++){
            Message msg = new Message("nx-user-sync"  ,
                    "beijing",
                    ("hello everybody" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.send(msg);
            System.out.printf("%s%n%n%n", sendResult.getSendStatus()+":(MsgId):"
                    +sendResult.getMsgId()+":(queueId):"
                    +sendResult.getMessageQueue().getQueueId()
                    +"(value):"+ new String(msg.getBody()));
        }


        producer.shutdown();
    }
}
